<?php
namespace Home\Controller;

class OrderController extends CommonController{

	public function index(){

	    $this->display();
    }
    
    public function addOrder(){
        $order_info = session('ready_order');
        $order  = array();
        if(!empty($order_info)){
            unset($order_info['goods_name'],$order_info['goods_desc'],$order_info['goods_pic'],$order_info['contain_service']);
        }else{
            $this->error('无效的订单信息');
        }
//         var_dump($order,session('order_datas'));exit;
        //添加订单数据
        $result = D('OrderInfo')->add($order_info);

        //添加order_goods
        if($result){
            $order_id = D('OrderInfo')->where("user_id='{$order_info['user_id']}' and order_sn='{$order_info['order_sn']}'")->getField('order_id');
            $order_datas = session('order_datas');
            if(I('post.pact'))$order_datas['pact_desc'] = I('post.pact');
            $this->addOrderGoods($order_id,$order_datas);
            session('order_datas',null);
            $this->success('下单成功！',U('Ucenter/orderList'));
        }
        $this->error('下单失败！');
    }
    
    private function addOrderGoods($order_id,$order_datas){
        $order_goods = array();
        if($order_datas['is_package'] == '1'){
            $goods_data = D('GoodsActivity')->where()->find();
            $order_goods['order_id'] = $order_id;
            $order_goods['goods_id'] = $goods_data['act_id'];
            $order_goods['goods_name'] = $goods_data['act_name'];
            $order_goods['goods_number'] = '1';
            $ext_info = unserialize($goods_data['ext_info']);
            $order_goods['market_price'] = $ext_info['package_price'];
            $order_goods['goods_price'] = $ext_info['package_price'];
            $order_goods['extension_code'] = 'package_buy';
        }else {
            $goods_data = D('Goods')->where("goods_id='{$order_datas['goods_id']}'")->find();
            $order_goods['order_id'] = $order_id;
            $order_goods['goods_id'] = $goods_data['goods_id'];
            $order_goods['goods_name'] = $goods_data['goods_name'];
            $order_goods['goods_sn'] = $goods_data['goods_sn'];
            $order_goods['goods_number'] = '1';
            $order_goods['market_price'] = $goods_data['market_price'];
            $order_goods['goods_price'] = $goods_data['shop_price'];
        }
        $order_goods['pact_desc'] = $order_datas['pact_desc'];
        if($guide_data = session('guide_data')){
            $order_goods['user_data'] = serialize($guide_data);
            session('guide_data',null);
        }
        if($order_datas['is_jinchukou'] !== null){
            $order_goods['user_data'] = serialize(array('jinchukou'=>$order_datas['is_jinchukou']));
        }
        D('OrderGoods')->add($order_goods);
        $extra_ids = array();
        if($order_datas['permit']) $extra_ids = $order_datas['permit'];
        if($order_datas['recommend_goods']) $extra_ids = array_merge($extra_ids,$order_datas['recommend_goods']);
        if(!empty($extra_ids)){
            foreach ($extra_ids as $val){
                $goods_data = D('Goods')->where("goods_id='$val'")->find();
                $order_goods = array();
                $order_goods['order_id'] = $order_id;
                $order_goods['goods_id'] = $goods_data['goods_id'];
                $order_goods['goods_name'] = $goods_data['goods_name'];
                $order_goods['goods_sn'] = $goods_data['goods_sn'];
                $order_goods['goods_number'] = '1';
                $order_goods['market_price'] = $goods_data['market_price'];
                $order_goods['goods_price'] = $goods_data['shop_price'];
                D('OrderGoods')->add($order_goods);
            }
        }
    }
    
    public function previewOrder(){
        $user = session('user');
        $consignee = D('UserAddress')->get_consignee($user['user_id']);
        $order = array(
            'order_sn' => get_order_sn(), //获取新订单号
            'user_id'         => $user['user_id'],
            'cp_id'         => $user['cp_id'],
            'add_time'        => time(),
            'update_time'    =>time(),
            'order_status'    => 0,
            'shipping_status' => 3,
            'pay_status'      => 0,
            'all_status'        =>3,
            'agency_id'       => D('Region')->get_agency_by_regions(array($consignee['country'], $consignee['province'], $consignee['city'], $consignee['district']))
        );
        /* 收货人信息 */
        $order = array_merge($order,$consignee);
        
        //组织order_goods信息
        if ($order_data = session('order_datas')){
            if($order_data['is_package'] == '1'){//如果是套餐
                $package_info = D('GoodsActivity')->where("act_id='{$order_data['goods_id']}'")->find();
                $ext_info = unserialize($package_info['ext_info']);
                $order['extension_code'] = 'package_buy';
                $order['goods_name'] = $package_info['act_name'];
                $order['goods_desc'] = $package_info['act_desc'];
                $order['goods_pic'] = $package_info['package_img'];
                $order['contain_service'] = $order['goods_name'];
                $order['order_amount'] = $ext_info['package_price'];
                if($order_data['is_jinchukou'] == '1'){
                    $order['order_amount'] += 2000;
                }
                if($order_data['spec_value'] == '2'){
                    $order['order_amount'] += 2000;
                }
                if(!empty($order_data['permit'])){
                    foreach ($order_data['permit'] as $val){
                        $goods = D('Goods')->where("goods_id='$val'")->find();
                        $order['order_amount'] += $goods['shop_price'];
                        $order['contain_service'] .= '、'.$goods['goods_name'];
                    }
                }
                if(!empty($order_data['recommend_goods'])){
                    foreach ($order_data['recommend_goods'] as $val){
                        $goods = D('Goods')->where("goods_id='$val'")->find();
                        $order['order_amount'] += $goods['shop_price'];
                        $order['contain_service'] .= '、'.$goods['goods_name'];
                    }
                }
            }else{
                $goods_info = D('Goods')->where("goods_id='{$order_data['goods_id']}'")->find();
                $order['goods_name'] = $goods_info['goods_name'];
                $order['goods_desc'] = $goods_info['goods_desc'];
                $order['goods_pic'] = $goods_info['goods_img'];
                $order['contain_service'] = $order['goods_name'];
                $order['order_amount'] = $goods_info['shop_price'];
                if(!empty($order_data['recommend_goods'])){
                    foreach ($order_data['recommend_goods'] as $val){
                        $goods = D('Goods')->where("goods_id='$val'")->find();
                        $order['order_amount'] += $goods['shop_price'];
                        $order['contain_service'] .= '、'.$goods['goods_name'];
                    }
                }
            }
        }else{
            $this->error('暂无订单信息');exit;
        }
        
        /* 如果订单金额为0（使用余额或积分或优惠卷支付），修改订单状态为已确认、已付款 */
        if ($order['order_amount'] <= 0){
            $order['order_status'] = 1;
            $order['confirm_time'] = time();
            $order['pay_status']   = 2;
            $order['pay_time']     = time();
            $order['order_amount'] = 0;
            $order['all_status'] = 11;
        }
        session('ready_order',$order);
        $this->assign('order_data',$order);
        $this->display();
    }
    
    public function orderReady(){
        $post_data = I('post.');
        session('order_datas',$post_data);
        $this->success('提交成功！',U('Order/previewOrder'));
    }
    
    public function getPact(){
        // 查询商品是否是套餐
        $sql="SELECT * FROM ".$cm->table('cart')." WHERE session_id = '" . SESS_ID . "' or user_id = '" . $_SESSION['user_id'] . "'" ;
        $g=$db->getRow($sql);
        if(empty($g)){
            $a['type']='error';
            $a['message']='请先选择你所需要的服务！';
            echo $json->encode($a);
            exit;
        }
        if($g['extension_code']!='package_buy'){
            // 获取订单所有商品
            $sql = "SELECT * FROM " . $cm->table('cart') .
            " as a,".$cm->table('goods')." as b WHERE a.goods_id=b.goods_id and (a.session_id = '" . SESS_ID . "' or a.user_id = '" . $_SESSION['user_id'] . "')" ;
            "AND a.parent_id = 0 AND a.is_gift = 0 AND a.rec_type = '$flow_type'";
            $pa=$db->getAll($sql);
        }else{
            $sql="SELECT * FROM ".$cm->table('goods')." WHERE goods_id IN(SELECT goods_id FROM ".$cm->table('package_goods')." AS pg WHERE pg.package_id='".$g['goods_id']."' ) ";
            $pa=$db->getAll($sql);
        }
        // 获取用户信息
        $sql='select * from '.$cm->table('users').' where user_id='.$user_id;
        $user=$db->getRow($sql);
        // 企业信息
        $sql='select * from '.$cm->table('company');
        $company=$db->getAll($sql);
        foreach ($company as $va) {
            $co[$va['cp_id']]=$va;
        }
        if(is_numeric($user['cp_id'])&&isset($co[$user['cp_id']])){
            $user['comname']=$co[$user['cp_id']]['cp_name'];
        }else{
            $user['comname']=!empty($user['name'])?$user['name']:$user['user_name'];
        }
        $smarty->assign('user', $user);
        // 获取关联数据
        $sql='select a.goods_id,b.* from '.$cm->table('goods_article').' as a,'.$cm->table('article').' as b where a.article_id=b.article_id and a.goods_id in (select goods_id from '.$cm->table('cart').' where session_id="'.SESS_ID.'" ) ';
        $art=$db->getAll($sql);
        foreach ($art as $v) {
            $artic[$v['goods_id']][]=$v;
        }
        $str='';
        foreach ($pa as $v) {
            // 判断商品是否存在属性
            $sql = 'SELECT goods_attr_id FROM '.$cm->table('cart').' WHERE goods_attr_id IS NOT NULL AND goods_id ="'.$v['goods_id'].'" AND session_id = "'.SESS_ID.'"';
            $attr = $db->getOne($sql);
            if(!empty($attr)){
                $attr = array_unique(explode(',', $attr));
                foreach ($attr as $key => $value) {
                    if(empty($value)) unset($attr[$key]);
                }
                $attr = implode(',',$attr);
                // 查询属性并生成字符串
                if(!empty($attr)){
                    $sql = 'SELECT * FROM '.$cm->table('goods_attr') .' WHERE goods_attr_id IN('.$attr.') AND goods_id ="'.$v['goods_id'].'"';
                    $v['gt'] = $db->getAll($sql);
                    // 获取相关的内容
                    $attrcont = array();
                    foreach ($v['gt'] as $ke => $val) {
                        $attrcont = array_merge($attrcont,explode(',', $val['attr_text']));
                    }
                    $attrcont = array_unique($attrcont);
                    $smarty->assign('attrcont', $attrcont);
                }
            }
            // if($v['goods_price']>0){
            // 咨询费（订单总价-3000）×70%+3000）
            // $v['consulting_price']=($v['shop_price']-3000)*0.7+3000;
            $v['consulting_price']=$v['is_flow_type']!=3 ? $v['goods_price']*0.7 : $v['goods_price'];
            $v['other_price']=$v['goods_price']-$v['consulting_price'];
            if(!empty($v['price']))$v['price']=sprintf("%.2f", $v['price']);
            if(!empty($v['consulting_price']))$v['consulting_price']=sprintf("%.2f", $v['consulting_price']);
            if(!empty($v['prepay_price']))$v['prepay_price']=sprintf("%.2f", $v['prepay_price']);
            if(!empty($v['goods_price']))$v['goods_price']=sprintf("%.2f", $v['goods_price']);
            if(!empty($v['other_price']))$v['other_price']=sprintf("%.2f", $v['other_price']);
            $smarty->assign('pact', $v);
            if(!isset($artic[$v['goods_id']])) $artic[$v['goods_id']]='';
            $smarty->assign('artic', $artic[$v['goods_id']]);
            $smarty->assign('goods_desc', $v['goods_desc']);
            $arr['goods_name'] = $v['goods_name'];
            $arr['comname'] = $user['comname'];
            $arr['orderyear'] = date('Y',time());
            $arr['ordermonth'] = date('m',time());
            $arr['orderday'] = date('d',time());
            // 商品价格
            //$arr['pactprice'] = ($g['extension_code']=='package_buy') ? $v['combo_price'] : $v['shop_price'];
            $arr['pactprice'] = $_REQUEST['pactprice'];
            // 1.面议/2.设立/3.物业/4.变更/5.代理记账/6.票据/7.中介/8.咨询/
            if($v['is_flow_type']==3){
                // $content=$smarty->fetch('pact1.dwt');
            }elseif($v['is_flow_type']==4){
                // $arr['pactprice'] = !empty($v['price']) ? $v['price'] : $v['goods_price'];
                $arr['consulting_price'] = !empty($v['consulting_price']) ? $v['consulting_price'] : '0.00';
                $arr['other_price'] = !empty($v['other_price']) ? $v['other_price'] : '0.00';
                $arr['prepay_price'] = !empty($v['prepay_price'])&&$v['prepay_price']!='0.00' ? $v['prepay_price'] : '1680.00';
                // $content=$smarty->fetch('pact4.dwt');
            }elseif($v['is_flow_type']==5){
                $arr['byear'] = date('Y',time());
                $arr['bmonth'] = date('m',time());
                $arr['bday'] = date('d',time());
                $arr['eyear'] = date('Y',time())+1;
            }else{
                if(isset($v['gt'])&&is_array($v['gt']))
                {
                    $pactcon='';
                    foreach ($v['gt'] as $i => $n)
                    {
                        if($i!=0)$pactcon.=',';
                        if(!empty($n['attr_value']))$pactcon.=$n['attr_value'];
                    }
                }
                $cont='';
                if(!empty($attrcont)&&is_array($attrcont))
                {
                    foreach ($attrcont as $i => $n)
                    {
                        $cont.='<p style="text-indent:37px;line-height:150%;background:white"><span style="font-size: 19px;line-height: 150%;font-family: 仿宋;border: 1px none windowtext;padding: 0">'.$n.'</span></p>';
                    }
                }else{
                    if(!empty($art)&&is_array($art))
                    {
                        foreach ($art as $i => $n)
                        {
                            $cont.='<p style="text-indent:37px;line-height:150%;background:white"><span style="font-size: 19px;line-height: 150%;font-family: 仿宋;border: 1px none windowtext;padding: 0">'.$n['title'].'</span></p>';
                        }
                    }
                }
                $arr['pactcon'] = isset($pactcon) ? $pactcon : '';
                $arr['cont'] = !empty($v['servecontent']) ? $v['servecontent'] : $cont;
                // $arr['pactprice'] = !empty($v['price']) ? $v['price'] : $v['goods_price'];
                $arr['consulting_price'] = !empty($v['consulting_price']) ? $v['consulting_price'] : '0.00';
                $arr['other_price'] = !empty($v['other_price']) ? $v['other_price'] : '0.00';
                $arr['prepay_price'] = !empty($v['prepay_price'])&&$v['prepay_price']!='0.00' ? $v['prepay_price'] : '1680.00';
                // $content=$smarty->fetch('pact.dwt');
            }
            // 替换
            $str .= repdwt($arr,$v['pact_desc']);
        
            //}
        }
        $a['content'] = $str;
        echo $json->encode($a);
    }
}
